<template>
    <section class="main" v-show="todos.length">
        <input id="toggle-all" class="toggle-all" type="checkbox" @change="onToggleAllChange" v-model="toggleAllState">
        <label for="toggle-all">Mark all as complete</label>
        <ul class="todo-list">
            <li class="todo" v-for="todo in todos" :key="todo.id" :class="{completed: todo.completed, editing: todo == editedTodo}">
                <div class="view">
                    <input :id="'todo-' + todo.id" class="toggle" type="checkbox" v-model="todo.completed">
                    <label :for="'todo-' + todo.id" @dblclick="onEditTodo(todo)">{{todo.title}}</label>
                    <button class="destroy" @click="onRemoveTodo(todo)"></button>
                </div>
                <input class="edit" type="text" v-model="todo.title" v-todo-focus="todo == editedTodo" @blur="onDoneEdit(todo)" @keyup.enter="onDoneEdit(todo)" @keyup.esc="onCancelEdit(todo)">
            </li>
        </ul>
    </section>
</template>
<script lang="ts">
import { ref } from 'vue'
/**
 * todo列表组件
 * 接收todos数组参数，展示代办数据
 */
export default {
    props: {
        todos: {
            type: Array,
            required: true
        },
        allDone: {
            type: Boolean,
            required: true
        },
        editedTodo: {
            type: Object,
        }
    },
    setup(props, context) {
        const toggleAllState = ref<boolean>(props.allDone)
        const onToggleAllChange = () => {
            context.emit('update:allDone', toggleAllState.value)
        }
        const onRemoveTodo = (todo) => {
            context.emit('removeTodo', {
                id: todo.id
            })
        }
        const onEditTodo = (todo) => {
            context.emit('editTodo', {
                id: todo.id
            })
        }
        const onDoneEdit = (todo) => {
            context.emit('doneEdit', {
                id: todo.id
            })
        }
        const onCancelEdit = (todo) => {
            context.emit('cancelEdit', {
                id: todo.id
            })
        }

        return {
            toggleAllState,
            onToggleAllChange,
            onRemoveTodo,
            onEditTodo,
            onDoneEdit,
            onCancelEdit
        }
    },
    directives: {
        'todo-focus': function (el, binding) {
            if (binding.value) {
                el.focus()
            }
        }
    }
}
</script>
